package com.mxc.split.config.algorithm;

import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;
import com.google.common.collect.Range;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.LinkedHashSet;

/**
 * @ClassName: PreciseModuloTableRangeShardingAlgorithm
 * @Description: 分表的自定义规则类(范围)
 * @author mengxc
 * @date 2020年9月29日 下午4:00:01
 */
public class PreciseModuloTableRangeShardingAlgorithm implements RangeShardingAlgorithm<String> {

	protected static final DateTimeFormatter dtfTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

	@Override
	public Collection<String> doSharding(Collection<String> availableTargetNames,
			RangeShardingValue<String> rangeShardingValue) {
		Range<String> ranges = rangeShardingValue.getValueRange();

		String lower = ranges.lowerEndpoint();
		String upper = ranges.upperEndpoint();

		LocalDateTime start = LocalDateTime.parse(lower, dtfTime);
		LocalDateTime end = LocalDateTime.parse(upper, dtfTime);

		int startYear = start.getYear();
		int endYear = end.getYear();

		int startMonth = start.getMonthValue();
		int endMonth = end.getMonthValue();

		Collection<String> tables = new LinkedHashSet<String>();
		if (start.isBefore(end) && (endYear - startYear) == 0 && (endMonth - startMonth) >= 0) {
			for (String c : availableTargetNames) {
				int cMonth = Integer.parseInt(c.substring(c.length() - 2, c.length()));
				if (cMonth >= startMonth && cMonth <= endMonth) {
					tables.add(c);
				}
			}
		}
		return tables;
	}
}